<?php

namespace app\common\exception;

use app\common\ErrorCode;
use think\Exception;
use Throwable;

class BusinessException extends Exception
{
    protected $code = ErrorCode::INTERNAL_SERVER_ERROR; // 默认业务错误码
    protected $message = '业务操作失败'; // 默认业务错误信息
    protected $data = []; // 额外数据，可用于携带更详细的错误信息或业务上下文

    public function __construct(
        string    $message = '',
        int       $code = 0,
        array     $data = [],
        Throwable $previous = null
    )
    {
        if ($message) {
            $this->message = $message;
        }
        if ($code) {
            $this->code = $code;
        }
        $this->data = $data;
        parent::__construct($this->message, $this->code, $previous);
    }


    // 方便链式调用设置数据
    public function withData(array $data): self
    {
        $this->data = array_merge($this->data, $data);
        return $this;
    }

}